package com.zsj.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yomahub.tlog.core.annotation.TLogAspect;
import com.zsj.channel.SpddService;
import com.zsj.config.ConfigBean;
import com.zsj.config.DataPool;
import com.zsj.context.ThreadLocalContext;
import com.zsj.entity.*;
import com.zsj.enums.AdCodeEnum;
import com.zsj.enums.CarrierCodeEnum;
import com.zsj.enums.ErrorCodeEnum;
import com.zsj.exception.BusinessException;
import com.zsj.service.MobileService;
import com.zsj.service.SignService;
import com.zsj.util.MoneyUtil;
import com.zsj.util.RegexValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 话费充值接口服务
 */
@RestController
@RequestMapping("/bytedance")
@Slf4j
public class MobileController {

    @Autowired
    private SignService signService;

    @Autowired
    private MobileService mobileService;

    @Autowired
    private SpddService spddService;

    @Autowired
    private ConfigBean configBean;

    @TLogAspect({"request.chargeNo"})
    @PostMapping(value = "/charge")
    public WebResponse recharge(@RequestBody RechargeRequest request) {
        log.info("话费/流量充值接⼝，请求参数:{}", JSONObject.toJSONString(request));
        try {
            // dy要求异常时响应报文也需要有Data字段，此处存储对象，在ResultProAdvice中赋值
            mobileService.buildRechargeDataBean(request, null, null);
            boolean flag = StringUtils.isBlank(request.getAppId())
                    || StringUtils.isBlank(request.getChargeNo())
                    || StringUtils.isBlank(request.getMobile())
                    || StringUtils.isBlank(request.getCarrierCode())
                    || StringUtils.isBlank(request.getAdCode())
                    || ObjectUtils.isEmpty(request.getTimestamp())
                    || StringUtils.isBlank(request.getNotifyUrl())
                    || StringUtils.isBlank(request.getProductDenomination())
                    || StringUtils.isBlank(request.getBizType())
                    || StringUtils.isBlank(request.getSubBizType())
                    || StringUtils.isBlank(request.getSign());
            if (flag) {
                log.info("必填项存在空");
                return WebResponse.fail(ErrorCodeEnum.PARAM_ERROR);
            }
            if (!MoneyUtil.isNumeric(request.getProductDenomination())) {
                log.info("金额格式错误");
                return WebResponse.fail(ErrorCodeEnum.PARAM_ERROR);
            }
            if (AdCodeEnum.findByCode(request.getAdCode()) == null) {
                log.info("省份code错误");
                return WebResponse.fail(ErrorCodeEnum.PARAM_ERROR);
            }

            CarrierCodeEnum cce = this.identify(request.getMobile());
            if (!request.getCarrierCode().equals(cce.getCode())) {
                log.info("运营商编码和实际手机号不匹配，订单号:{}, 手机号:{}, 传入的运营商编码:{}，查询的运营商编码:{}", request.getChargeNo(), request.getMobile(), request.getCarrierCode(), cce.getCode());
                if (configBean.getCheckCarrierCode()) { // 关闭携转验证，订单继续流转
                    return WebResponse.fail(ErrorCodeEnum.MOBILE_EXCEPTION);
                }
            }

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> requestMap = mapper.readValue(JSONObject.toJSONString(request), Map.class);
            // 验签
            signService.validateSign(requestMap);
            RechargeResponse response = mobileService.recharge(request);
            log.info("话费/流量充值接⼝响应为:{}", JSONObject.toJSONString(response));
            return WebResponse.success(JSONObject.toJSONString(response));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.info("话费/流量充值处理异常", e);
            return WebResponse.fail(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }

    @TLogAspect({"request.chargeNo"})
    @PostMapping(value = "/query")
    public WebResponse orderQuery(@RequestBody OrderQueryRequest request) {
        log.info("充值订单查询接⼝，请求参数:{}", JSONObject.toJSONString(request));
        try {
            mobileService.buildRechargeDataBean(request, null, null);
            boolean flag = StringUtils.isBlank(request.getAppId())
                    || StringUtils.isBlank(request.getChargeNo())
                    || ObjectUtils.isEmpty(request.getTimestamp())
                    || StringUtils.isBlank(request.getSign());
            if (flag) {
                log.info("必填项存在空");
                return WebResponse.fail(ErrorCodeEnum.PARAM_ERROR);
            }

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> requestMap = mapper.readValue(JSONObject.toJSONString(request), Map.class);
            // 验签
            signService.validateSign(requestMap);
            RechargeResponse response = mobileService.orderQuery(request);
            log.info("充值订单查询接⼝响应为:{}", JSONObject.toJSONString(response));
            return WebResponse.success(JSONObject.toJSONString(response));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.info("充值订单查询处理异常", e);
            return WebResponse.fail(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }

    @PostMapping(value = "/queryMaintain")
    public WebResponse productQuery(@RequestBody ProductQueryRequest request) {
        log.info("维护信息查询接⼝，请求参数:{}", JSONObject.toJSONString(request));

        // 所有商品一键维护
        log.info("DataPool.maintenanceAllProduct: {}", DataPool.maintenanceAllProduct);
        if (DataPool.maintenanceAllProduct) {
            ProductQueryResponse response = spddService.productMaintenanceAll();

            log.info("已经一键维护所有商品");
            return WebResponse.success(JSONObject.toJSONString(response.getMaintainInfo()));
        }

        try {
            ThreadLocalContext.RECHARGE_DATA_THREAD_LOCAL.set("[]");
            boolean flag = StringUtils.isBlank(request.getAppId())
                    || StringUtils.isBlank(request.getSupplierCode())
                    || ObjectUtils.isEmpty(request.getTimestamp())
                    || StringUtils.isBlank(request.getSign());
            if (flag) {
                log.info("必填项存在空");
                return WebResponse.fail(ErrorCodeEnum.PARAM_ERROR);
            }

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> requestMap = mapper.readValue(JSONObject.toJSONString(request), Map.class);
            // 验签
            signService.validateSign(requestMap);
            ProductQueryResponse response = mobileService.productQuery(request);
            log.info("维护信息查询接⼝响应为:{}", JSONObject.toJSONString(response));
            return WebResponse.success(JSONObject.toJSONString(response.getMaintainInfo()));
        } catch (BusinessException be) {
            throw be;
        } catch (Exception e) {
            log.info("维护信息查询处理异常", e);
            return WebResponse.fail(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }

    private CarrierCodeEnum identify(String phoneNumber) {
        if (RegexValidateUtil.validate(configBean.getCmPhoneNumberRegex(), phoneNumber)) {
            return CarrierCodeEnum.CM;
        } else if (RegexValidateUtil.validate(configBean.getCtPhoneNumberRegex(), phoneNumber)) {
            return CarrierCodeEnum.CT;
        } else if (RegexValidateUtil.validate(configBean.getCuPhoneNumberRegex(), phoneNumber)) {
            return CarrierCodeEnum.CU;
        } else {
            return CarrierCodeEnum.CM;
        }
    }

}
